package db

import (
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"log"
	"strconv"
	"xiaoniu-job/internal/config"
	"xiaoniu-job/pkg"
)

var globalDb *gorm.DB

// InitDb 初始化数据库
func InitDb() {
	dsn := config.ServerRation.DataBaseUser + ":" + config.ServerRation.DataBasePwd + "@tcp(" + config.ServerRation.DataBaseHost +
		":" + strconv.Itoa(config.ServerRation.DataBasePort) + ")/" + config.ServerRation.DataBaseName +
		"?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		//Logger: logger.Default.LogMode(logger.Info),
	})
	if err != nil {
		log.Println("初始化数据库报错：", err)
	}
	globalDb = db
	globalDb.AutoMigrate(pkg.Task{})
	globalDb.AutoMigrate(pkg.JobLog{})
	globalDb.AutoMigrate(pkg.Executor{})
}

func GetGlobalDb() *gorm.DB {
	return globalDb
}
